const state = {
	messages: [],
	isSending: false,
	uuid: null,
	userId: null
};

document.addEventListener('DOMContentLoaded', function() {


	if (!Auth.isLoggedIn()) {
		alert('请先登录');
		window.location.href = 'login.html';
		return;
	}

	// 原有代码保持不变
	state.userId = Auth.getCurrentUserId();

	// 初始化
	initUUID();
	hello();

	// 设置事件监听器
	document.getElementById('sendBtn').addEventListener('click', sendMessage);
	document.getElementById('messageInput').addEventListener('keyup', function(e) {
		if (e.key === 'Enter') sendMessage();
	});
	document.getElementById('newChatBtn').addEventListener('click', newChat);

	// 功能函数
	function scrollToBottom() {
		const messageList = document.getElementById('messageList');
		if (messageList) {
			messageList.scrollTop = messageList.scrollHeight;
		}
	}

	function hello() {
		sendRequest('你好');
	}

	function sendMessage() {
		const input = document.getElementById('messageInput');
		if (input.value.trim()) {
			sendRequest(input.value.trim());
			input.value = '';
		}
	}

	function sendRequest(message) {
		if (!state.userId) {
			alert('请先登录');
			window.location.href = 'login.html';
			return;
		}

		const messageWithMeta = JSON.stringify({
			userId: state.userId,
			content: message
		});

		state.isSending = true;
		const userMsg = {
			isUser: true,
			content: message,
			isTyping: false,
			isThinking: false
		};

		// 第一条默认发送的用户消息"你好"不放入会话列表
		if (state.messages.length > 0) {
			state.messages.push(userMsg);
			renderMessage(userMsg);
		}

		// 添加机器人加载消息
		const botMsg = {
			isUser: false,
			content: '',
			isTyping: true,
			isThinking: false
		};
		state.messages.push(botMsg);
		renderMessage(botMsg);
		scrollToBottom();

		const lastMsgIndex = state.messages.length - 1;

		axios.post('http://localhost:8080/xiaozhi/chat', {
				memoryId: state.uuid,
				message: messageWithMeta
			}, {
				responseType: 'text',
				onDownloadProgress: function(e) {
					const fullText = e.event.target.responseText;
					let newText = fullText.substring(state.messages[lastMsgIndex].content.length);
					state.messages[lastMsgIndex].content += newText;
					updateMessage(lastMsgIndex);
					scrollToBottom();
				}
			})
			.then(function() {
				state.messages[lastMsgIndex].isTyping = false;
				updateMessage(lastMsgIndex);
				state.isSending = false;
			})
			.catch(function(error) {
				console.error('流式错误:', error);
				state.messages[lastMsgIndex].content = '请求失败，请重试';
				state.messages[lastMsgIndex].isTyping = false;
				updateMessage(lastMsgIndex);
				state.isSending = false;
			});
	}

	function initUUID() {
		let storedUUID = localStorage.getItem('user_uuid');
		if (!storedUUID) {
			// 生成一个6位纯数字的随机数作为 UUID 替代方案
			storedUUID = Math.floor(Math.random() * 900000) + 100000; // 生成一个6位的随机数字
			localStorage.setItem('user_uuid', storedUUID.toString()); // 存储时转换为字符串
		}
		state.uuid = parseInt(storedUUID); // 读取时确保是数字
	}

	function convertStreamOutput(output) {
		// 先处理基本的HTML转义
		let result = output
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;');

		// 处理Markdown格式
		// 标题
		result = result.replace(/^### (.*$)/gm, '<h3>$1</h3>');
		result = result.replace(/^## (.*$)/gm, '<h2>$1</h2>');
		result = result.replace(/^# (.*$)/gm, '<h1>$1</h1>');

		// 无序列表
		result = result.replace(/^\s*[-*+] (.*$)/gm, '<li>$1</li>');
		result = result.replace(/(<li>.*<\/li>)+/g, function(match) {
			return '<ul>' + match + '</ul>';
		});

		// 有序列表
		result = result.replace(/^(\s*\d+\. .*(?:\n\s*\d+\. .*)*)/gm, function(match) {
			// 对每一行进行处理
			return match.replace(/^\s*(\d+)\. (.*$)/gm, '<li value="$1">$2</li>');
		});
		// 然后将连续的<li>包裹在<ol>中
		result = result.replace(/(<li value="\d+">.*<\/li>)+/g, function(match) {
			return '<ol>' + match + '</ol>';
		});

		// 引用
		result = result.replace(/^> (.*$)/gm, '<blockquote>$1</blockquote>');

		// 代码块
		result = result.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');

		// 行内代码
		result = result.replace(/`([^`]+)`/g, '<code>$1</code>');

		// 加粗
		result = result.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
		result = result.replace(/__(.*?)__/g, '<strong>$1</strong>');

		// 斜体
		result = result.replace(/\*(.*?)\*/g, '<em>$1</em>');
		result = result.replace(/_(.*?)_/g, '<em>$1</em>');

		// 换行处理
		result = result.replace(/\n/g, '<br>');

		// 缩进处理
		result = result.replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');

		return result;
	}

	function newChat() {
		localStorage.removeItem('user_uuid');
		window.location.reload();
	}

	function renderMessage(message) {
		const messageList = document.getElementById('messageList');
		if (!messageList) return;

		const messageDiv = document.createElement('div');
		messageDiv.className = `message ${message.isUser ? 'user-message' : 'bot-message'}`;

		const icon = document.createElement('i');
		icon.className = `message-icon fa-solid ${message.isUser ? 'fa-user' : 'fa-robot'}`;

		const contentSpan = document.createElement('span');
		contentSpan.innerHTML = convertStreamOutput(message.content);

		if (message.isTyping || message.isThinking) {
			const loadingSpan = document.createElement('span');
			loadingSpan.className = 'loading-dots';

			const dot1 = document.createElement('span');
			dot1.className = 'dot';

			const dot2 = document.createElement('span');
			dot2.className = 'dot';

			loadingSpan.appendChild(dot1);
			loadingSpan.appendChild(dot2);
			contentSpan.appendChild(loadingSpan);
		}

		if (message.isUser) {
			messageDiv.appendChild(contentSpan);
			messageDiv.appendChild(icon);
		} else {
			messageDiv.appendChild(icon);
			messageDiv.appendChild(contentSpan);
		}

		messageList.appendChild(messageDiv);
	}

	function updateMessage(index) {
		const messageList = document.getElementById('messageList');
		if (!messageList || index >= messageList.children.length) return;

		const messageDiv = messageList.children[index];
		const contentSpan = messageDiv.querySelector('span:not(.loading-dots)');
		const loadingSpan = messageDiv.querySelector('.loading-dots');

		if (contentSpan) {
			contentSpan.innerHTML = convertStreamOutput(state.messages[index].content);
		}

		if (loadingSpan) {
			if (state.messages[index].isTyping || state.messages[index].isThinking) {
				loadingSpan.style.display = 'inline';
			} else {
				loadingSpan.style.display = 'none';
			}
		}
	}
});